package com.example.redis.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

/**
 * redis 发布订阅功能
 *
 * @author luowj12
 * @since 2021/5/26 17:25
 */
@RestController
@RequestMapping("ps")
@Api(tags="Redis发布订阅功能api")
public class PubSubController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发布者
     * @param message
     */
    @PostMapping("/publish")
    @ApiOperation("发布者接口")
    public void publish(@RequestParam(value = "message") String message) {
        redisTemplate.convertAndSend("news", message);

    }


    /**
     * subscribe 订阅者
     */
    class MyRedisChannelListener implements MessageListener {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            byte[] channel = message.getChannel();
            byte[] body = message.getBody();

            try {
                String content = new String(body,"UTF-8");
                String address = new String(channel,"UTF-8");
                System.out.println("get " + content + " from " + address);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }


    @Bean
    MessageListenerAdapter messageListenerAdapter() {
        return new MessageListenerAdapter(new MyRedisChannelListener());
    }

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // news 频道名称
        container.addMessageListener(listenerAdapter, new PatternTopic("news"));
        return container;
    }

}
